class EntryController {

  def index = { redirect(action: list, params: params) }

  // the delete, save and update actions only accept POST requests
  static allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

  def list = {
    params.max = Math.min(params.max ? params.max.toInteger() : 30, 100)
    [entryInstanceList: Entry.list(params), entryInstanceTotal: Entry.count()]
  }

  def show = {
    def entryInstance = Entry.get(params.id)
    if (!entryInstance) {
      flash.message = "Entry not found with id ${params.id}"
      redirect(action: list)
    }
    else { return [entryInstance: entryInstance] }
  }

  def about = {
    def entryInstance = Entry.get(params.id)
    if (!entryInstance) {
      flash.message = "Entry not found with id ${params.id}"
      redirect(action: list)
    }
    else { return [entryInstance: entryInstance] }
  }


  def ajaxshow = {
    def entryInstance = Entry.get(params.id)
    if (!entryInstance) {
      render "Entry not found with id ${params.id}"
      return
    }
    else {
      return [entryInstance: entryInstance]
    }
  }

  def preview = {
    def entryInstance = Entry.get(params.id)
    if (!entryInstance) {
      flash.message = "Entry not found with id ${params.id}"
      render "not found it."
    }
    else { return [entryInstance: entryInstance, offset: params.offset] }
  }

  def delete = {
    def entryInstance = Entry.get(params.id)
    if (entryInstance) {
      try {
        entryInstance.delete()
        flash.message = "Entry ${params.id} deleted"
        redirect(action: list)
      }
      catch (org.springframework.dao.DataIntegrityViolationException e) {
        flash.message = "Entry ${params.id} could not be deleted"
        redirect(action: show, id: params.id)
      }
    }
    else {
      flash.message = "Entry not found with id ${params.id}"
      redirect(action: list)
    }
  }

  def edit = {
    def entryInstance = Entry.get(params.id)

    if (!entryInstance) {
      flash.message = "Entry not found with id ${params.id}"
      redirect(action: list)
    }
    else {
      return [entryInstance: entryInstance]
    }
  }

  def update = {
    def entryInstance = Entry.get(params.id)
    if (entryInstance) {
      if (params.version) {
        def version = params.version.toLong()
        if (entryInstance.version > version) {

          entryInstance.errors.rejectValue("version", "entry.optimistic.locking.failure", "Another user has updated this Entry while you were editing.")
          render(view: 'edit', model: [entryInstance: entryInstance])
          return
        }
      }
      entryInstance.properties = params
      entryInstance.tagNames?.tokenize(", ").each {
        entryInstance.parseTags(it)
      }
      def tagnames = entryInstance.tagNames?.tokenize(", ")
      entryInstance.tags.each {
        if (!tagnames.contains(it)) {
          entryInstance.removeTag(it)
        }
      }
      if (entryInstance.catalog) {
        entryInstance.depth = entryInstance.catalog.depth
      }

      if (!entryInstance.hasErrors() && entryInstance.save()) {
        flash.message = "Entry ${params.id} updated"
        redirect(action: show, id: entryInstance.id)
      }
      else {
        render(view: 'edit', model: [entryInstance: entryInstance])
      }
    }
    else {
      flash.message = "Entry not found with id ${params.id}"
      redirect(action: edit, id: params.id)
    }
  }

  def create = {
    def entryInstance = new Entry()
    entryInstance.properties = params
    return ['entryInstance': entryInstance]
  }


  def imp = {
    def entryInstance = new Entry(params)
    if (entryInstance.catalog) {
      entryInstance.depth = entryInstance.catalog.depth
    }
    if (!entryInstance.hasErrors() && entryInstance.save()) {
      render "0"
    } else {
      render entryInstance.errors
    }
  }

  def save = {
    def entryInstance = new Entry(params)
    if (entryInstance.catalog) {
      entryInstance.depth = entryInstance.catalog.depth
    }

    //auto remember last keyit option
    if (session['keyit']) {
      if (entryInstance.catalog) {
        session['keyit.catalog.id'] = entryInstance.catalog.id
      }
      if (entryInstance.stage) {
        session['keyit.stage'] = entryInstance.stage
      }
    }

    if (!entryInstance.hasErrors() && entryInstance.save()) {
      if (entryInstance.tagNames) {
        entryInstance.parseTags(entryInstance.tagNames)
      }
      flash.message = "Entry ${entryInstance.id} created"
      redirect(action: show, id: entryInstance.id)
    }
    else {
      render(view: 'create', model: [entryInstance: entryInstance])
    }
  }

  def news = {

    def rootCatalog = Catalog.findByNameAndRootCatalogIdIsNull("news")
    def entryList = []
    def total = 0
    if (rootCatalog) {
      total = Entry.countByRootCatalogId(rootCatalog.id)
      if (total > 0) {
        entryList = Entry.findAllByRootCatalogId(rootCatalog.id, [max: 10, sort: 'desc', order: 'dateCreated'])
      }
    }
    [entryList: entryList, total: total]
  }

  def lessons = {
    def baby = Baby.get(params.id)
    def stage = babyService.getStage(baby)
    def startStage = stage - 15
    def endStage = stage + 15
    def entryList = []
    def total = 0
    def rootCatalog = Catalog.findByNameAndRootCatalogIdIsNull("lessons")
    if (rootCatalog) {
      def sql = "from Entry as t where t.rootCatalogId is null and t.stage > :startStage and t.stage < :endStage"
      entryList = Entry.findAll(sql, [startStage: startStage, endStage: endStage], [sort: 'desc', order: 'dateCreated'])
      total = Entry.executeQuery("select count(*) from " + sql, [startStage: startStage, endStage: endStage])[0].toInteger()
    }
    [entryList: entryList, total: total]
  }

  def graspService
  def keyit = {
    println params
    session['keyit'] = true
    if (session['keyit.catalog.id']) params['catalog.id'] = session['keyit.catalog.id']
    if (session['keyit.stage']) params['stage'] = session['keyit.stage']

    def entryInstance = new Entry()
    entryInstance.properties = params

    graspService.grasp(params.sourceUrl, entryInstance)
    return ['entryInstance': entryInstance]
  }

  def saveit = {
    def entryInstance = new Entry(params)
    if (entryInstance.catalog) {
      entryInstance.depth = entryInstance.catalog.depth
    }
    if (entryInstance.tagNames) {
      entryInstance.parseTags(entryInstance.tagNames)
    }
    if (!entryInstance.hasErrors() && entryInstance.save()) {
      flash.message = "Entry ${entryInstance.id} created"
      def content = """
        <p> Entry created！</p>
        <p><input type="button" action="javascript:window.close();" value="close"/></p>
              """
      render content
    }
    else {
      def content = """
        <p> Entry not create！</p>
        <p>${entryInstance.errors}</p>
        <p><input type="button" action="javascript:window.close();" value="close"/></p>
              """
      render content
    }
  }

  /** *
   * ajax update
   */


  def ajaxstage = {
    def entryInstance = Entry.get(params.id)
    if (!entryInstance) render '-1'
    if (params.stage) {
      entryInstance.stage = params.stage.toInteger()
      entryInstance.save()
    }
    render entryInstance.stage.toString()
  }

  def ajaxlist = {
    params.max = Math.min(params.max ? params.max.toInteger() : 30, 100)
    [entryInstanceList: Entry.list(params), entryInstanceTotal: Entry.count()]
  }

  def contentupdate = {
    def id = params.id
    if(!params.offset)
    	params.offset = 0
    def entryInstance = Entry.get(id)
    def content = entryInstance.content
    entryInstance.content = params.content
    entryInstance.save(flush: true)
    println entryInstance.errors
    if (!entryInstance.hasErrors() && entryInstance.save()) {
      params.max = Math.min(params.max ? params.max.toInteger() : 30, 100)
      render(view: 'list', model: [entryInstanceList: Entry.list(params), entryInstanceTotal: Entry.count()])
    } else {
      render(view: 'edit', model: [entryInstance: entryInstance])
    }
  }


  def titleupdate = {
    println params
    def id = params.id
    def entryInstance = Entry.get(id)
    def title = entryInstance.title
    entryInstance.title = params.value
    entryInstance.save(flush: true)
    println entryInstance.errors
    if (!entryInstance.hasErrors() && entryInstance.save()) {
      render(params.value)
    } else {
      render(title)
    }
  }

  def ajaxdelete = {
    println params
    def entry = Entry.get(params.id)
    entry.delete()
    println entry.errors
    if (!entry.hasErrors()) {
      render 'success'
    } else {
      render 'fail'
    }
  }

  def fckedit = {
    def entry = Entry.get(27)
    println entry
    return render(view: 'fckedit', model: [entry: entry])
  }


  def updatecategory = {
  }

}
